Factory Methodパターン
code:framework.Product.java
package framework;
public abstract class Product {
public abstract void use();
}
code:framework.Factory.java
package framework;
public abstract class Factory {
public final Product create(String owner) {
Product p = createProduct(owner);
registerProduct(p);
return p;
}
protected abstract Product createProduct(String owner);
protected abstract void registerProduct(Product product);
}
code:idcard.IDCard.java
package idcard;
import framework.*;
public class IDCard extends Product {
private String owner;
IDCard(String owner) {
System.out.println(owner + "のカードを作ります。");
this.owner = owner;
}
public void use() {
System.out.println(owner + "のカードを使います。");
}
public String getOwner() {
return owner;
}
}
code:idcard.IDCardFactory.java
package idcard;
import framework.*;
import java.util.*;
public class IDCardFactory extends Factory {
private List owners = new ArrayList();
protected Product createProduct(String owner) {
return new IDCard(owner);
}
protected void registerProduct(Product product) {
owners.add(((IDCard)product).getOwner());
}
public List getOwners() {
return owners;
}
}
code:Main.java
import framework.*;
import idcard.*;
public class Main {
public static void main(String[] args) {
Factory factory = new IDCardFactory();
Product card1 = factory.create("結城浩");
Product card2 = factory.create("とむら");
Product card3 = factory.create("佐藤花子");
card1.use();
card2.use();
card3.use();
}
}